import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { RootState } from '../store';
import { addTab, removeTab, setActiveTab } from '../store/slices/tabs';

// interface Tab {
//   title: string;
//   path: string;
// }

/**
 * 自定义标签页Hook，提供标签页的添加、删除和激活功能
 */
const useTabs = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { tabs, activeTab } = useSelector((state: RootState) => state.tabs);
  const { menus } = useSelector((state: RootState) => state.menu);

  /**
   * 添加标签页
   * @param path 路径
   * @param title 标题（可选，如果不提供则从菜单中查找）
   */
  const add = useCallback(
    (path: string, title?: string) => {
      // 如果是首页，不添加标签
      if (path === '/home' || path === '/') {
        dispatch(setActiveTab('/home'));
        return;
      }

      // 如果没有提供标题，从菜单中查找
      if (!title) {
        menus.forEach((menu) => {
          if (menu.children) {
            const child = menu.children.find((child) => child.path === path);
            if (child) {
              title = child.title;
            }
          }
        });
      }

      // 如果还是没有标题，使用路径的最后一段
      if (!title) {
        const pathSegments = path.split('/');
        title = pathSegments[pathSegments.length - 1];
        // 首字母大写
        title = title.charAt(0).toUpperCase() + title.slice(1);
      }

      dispatch(addTab({ title, path }));
    },
    [dispatch, menus]
  );

  /**
   * 移除标签页
   * @param targetPath 要移除的标签页路径
   */
  const remove = useCallback(
    (targetPath: string) => {
      // 不允许移除首页
      if (targetPath === '/home') {
        return;
      }

      dispatch(removeTab(targetPath));

      // 如果移除的是当前激活的标签页，需要导航到新的激活标签页
      if (activeTab === targetPath) {
        const currentIndex = tabs.findIndex((tab) => tab.path === targetPath);
        let newPath = '/home';

        if (currentIndex > 0) {
          // 优先选择前一个标签
          newPath = tabs[currentIndex - 1].path;
        } else if (tabs.length > 1 && currentIndex === 0) {
          // 如果是第一个标签，选择下一个标签
          newPath = tabs[1].path;
        }

        navigate(newPath);
      }
    },
    [dispatch, navigate, activeTab, tabs]
  );

  /**
   * 激活标签页
   * @param path 标签页路径
   */
  const setActive = useCallback(
    (path: string) => {
      dispatch(setActiveTab(path));
      navigate(path);
    },
    [dispatch, navigate]
  );

  return {
    tabs,
    activeTab,
    addTab: add,
    removeTab: remove,
    setActiveTab: setActive
  };
};

export default useTabs; 